﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Media;
using System.Text;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Reflection;
using System.Resources;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using libvkontakte;
using System.Drawing;
using Hardcodet.Wpf.TaskbarNotification;
using VkontakteChecker.Logic;
using VkontakteChecker.Showcase;

namespace VkontakteChecker
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        private SoundPlayer player = new SoundPlayer();
        object locker = new object();

        public MainWindow()
        {
            InitializeComponent();
            Hide();
            MyIcon.TrayMouseDoubleClick += new RoutedEventHandler(MyIcon_TrayMouseDoubleClick);
            Actions.InitializeUser();
            Process();
        }

        void MyIcon_TrayMouseDoubleClick(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://vkontakte.ru");
        }

        private void ShowErrorBallon(string maintext)
        {
            FancyBaloon ballon = new FancyBaloon();
            ballon.MainText.Text = maintext;
            
            ballon.HeaderText.Text = "Оповещение";
            MyIcon.ShowCustomBalloon(ballon, PopupAnimation.Slide, 5000);
            SoundPlayer player = new SoundPlayer(Properties.Resources.vk_sound);
            player.Play();
        }

        private void ShowBallon(string text)
        {
            FancyBaloon ballon = new FancyBaloon();
            ballon.MainText.Text = text;
            ballon.HeaderText.Text = "У вас есть новые события:";
            MyIcon.ShowCustomBalloon(ballon, PopupAnimation.Slide, 6000);
            SoundPlayer player = new SoundPlayer(Properties.Resources.vk_sound);
            player.Play();
        }

        private void MenuItemExit_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        
        private void MenuItemSettings_Click(object sender, RoutedEventArgs e)
        {
            var window = new SettingsWindow();
            window.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
            window.ShowDialog();
        }


        private void MenuItemCheck_Click(object sender, RoutedEventArgs e)
        {
            Process();
        }

        private void MenuItemTrayDoubleClick(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://vkontakte.ru/mail.php?act=write");
        }

        public void Process()
        {
            Thread thread = new Thread(Test);
            thread.IsBackground = true;
            thread.Start();
        }

        private void Test()
        {
            while(true)
            {
                int time = Settings.Period*60000;           

                if (!Actions.IsInitializedUser())
                   ShowErrorBalloonFromThread("Отсутствуют email и пароль.");


                if (!Actions._isConnectionAvialable)
                {
                    time = Settings.MinTime;
                    Actions.CheckConnection();
                    ShowErrorBalloonFromThread(Actions._isConnectionAvialable.ToString());
                    Thread.Sleep(time);
                    continue;
                }

                if (!Actions._user.IsLogin() && Actions.IsInitializedUser()  )
                {
                    ShowErrorBalloonFromThread("Подключаемся...");
                    try
                    {
                        Actions.LoginUser();
                    }
                    catch(Exception exception)
                    {
                        ShowErrorBalloonFromThread("Отсутствует соединение.");
                        Actions._isConnectionAvialable = false;
                        time = Settings.MinTime;
                    }
                }

                if(!Actions._user.IsLogin())
                {
                    ShowErrorBalloonFromThread("Неверный логин или пароль");
                }

                if(Actions._user.IsLogin() && Actions._isConnectionAvialable)
                {
                    time = Settings.Period*60000;
                    Dictionary<string,int> res = null; 
                    try
                    {
                       res = Actions._user.GetIndexes();
                    }
                    catch(Exception exception)
                    {
                        Actions._isConnectionAvialable = false;
                        time = Settings.MinTime;
                    }

                    if(res != null && res.Count > 0)
                    {
                        StringBuilder sb = new StringBuilder();
                        foreach (var i in res)
                        {
                            if(i.Value != 0)
                                sb.Append(i.Key + ": " + i.Value + "\n");
                        }
                        ShowBalloonFromThread(sb.ToString());
                    }
                }
                
                Thread.Sleep(time);
            }
        }

        private void ShowBalloonFromThread(string text)
        {
            ThreadStart start = delegate()
            {
                DispatcherOperation op = Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                                                new Action<string>(ShowBallon),text);
            };
            new Thread(start).Start();
        }

        private void ShowErrorBalloonFromThread(string text)
        {
            ThreadStart start = delegate()
            {
                DispatcherOperation op = Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                                                new Action<string>(ShowErrorBallon), text);
            };
            new Thread(start).Start();
        }
    }
}
